package com.shouhuyun.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shouhuyun.constant.RedisConstant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shouhuyun.dao.PermissionDao;
import com.shouhuyun.dao.RoleDao;
import com.shouhuyun.dao.UserDao;
import com.shouhuyun.entity.PageResult;
import com.shouhuyun.entity.QueryPageBean;
import com.shouhuyun.entity.PageResult;
import com.shouhuyun.entity.QueryPageBean;
import com.shouhuyun.pojo.CheckItem;
import com.shouhuyun.pojo.Permission;
import com.shouhuyun.pojo.Role;
import com.shouhuyun.pojo.User;
import com.shouhuyun.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


import java.util.List;
import java.util.Set;


/**
 * 用户服务
 */

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private JedisPool jedisPool;



    @Override
    public PageResult Pagequery(QueryPageBean queryPageBean) throws Exception {
        //三个参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //分页查询的插件   放入当前页面和页面大小参数
        //会通过自己封装的拦截器  拦截我们的sql语句  自动添加 limit分页
        PageHelper.startPage(currentPage,pageSize);

        //根据条件查询
        Page<User> page = userDao.findByCondition(queryString);
        List<User> result = page.getResult();

        /*for (User user : result) {
            Date birthday = user.getBirthday();
            *//*long milliSecond = 1551798059000L;
            Date date = new Date();
            date.setTime(milliSecond);*//*
            if (birthday != null){
                String format = new SimpleDateFormat().format(birthday);
                Date date = DateUtils.parseString2Date(format);
                user.setBirthday(date);
            }
        }*/

        return new PageResult(page.getTotal(),result);
    }
    //毫秒值 转换成日期格式的字符串
    public String secondToDate(long second,String patten) {
        Calendar calendar = Calendar.getInstance();
        // calendar.setTimeInMillis(second * 1000);//转换为毫秒
        calendar.setTimeInMillis(second);//转换为毫秒

        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(patten);
        String dateString = format.format(date);
        return dateString;
    }

    //根据用户名查询数据库获取用户信息和关联的角色信息  同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        //1. 查找用户的基本信息
        User user = userDao.findByUsername(username);
        if (user == null){
            return null;
        }
        Integer userId = user.getId();
        // 2. 根据用户id查询所拥有的 角色 集合
        Set<Role> roles =  roleDao.findByUserId(userId);
        // 3. 遍历角色集合  查询关联的权限
        for (Role role : roles) {
            Integer roleId = role.getId();
            // 3.1 根据角色id查找 该角色所拥有的的权限
            Set<Permission> permissions =  permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions); // 让角色关联权限
        }
        user.setRoles(roles); // 让用户关联角色
        return user;
    }




    @Override
    public void add(User user, Integer[] roleIds) throws ParseException {
        userDao.add(user);

        Integer id = user.getId();
        if (roleIds != null && roleIds.length > 0) {
            //绑定套餐和检查组的多对多的关系
            setRole(id, roleIds);
        }
        //将图片名称保存到redis   方法抽取在60行
        savePic2Redis(user.getImg());
    }
    //    将图片保存到Redis里 的方法抽取
    private void savePic2Redis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

    @Override
    public void edit(Integer id, Integer[] roleIds) {
        //先清理关联关系   清理当前套餐关联的检查组
        userDao.deleteAssociation(id);
        //在建立新的关联
        Integer userId = id;
        //遍历检查项数据
        this.setRole(userId,roleIds);
    }

    @Override
    public List<Integer> findById(Integer id) {
        return userDao.findById(id);
    }

    //    建立检查组和检查项多对多关系   方法抽取
    public void setRole(Integer id,Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            if (roleIds != null && roleIds.length > 0) {
                for (Integer ids : roleIds) {
                    //创建map集合
                    Map<String, Integer> map = new HashMap<>();
                    map.put("userId", id);
                    map.put("roleId", ids);
                    userDao.setRoleids(map);
                }
            }
        }
    }

    @Override
    public void updateNewByCondition(String username, String password) {
        userDao.updatepassword(username,password);
    }

    @Override
    public String findpasswordByusername(String username) {
        String password=userDao.findpasswordByusername(username);
        return password;
    }

    @Override
    public void deleteById(Integer id) {
        //        删除用户和角色的关系
        userDao.deleteByIdInUserAndRole(id);
//        删除套餐
        userDao.deleteById(id);
    }
}
